//################################
// 版权所有：中国农业银行软件开发中心
// 系统名称：移动办公应用-手机版
// 文件名称：myResetPwd.js
// 创建时间：2016年10月17日
// 创建人员：Lemo
// 功能说明：myResetPwd page
//################################
'use strict';

import React, {Component} from 'react';
import {
    View,
    StyleSheet,
    Text,
    TextInput,
    Image,
    Dimensions,
    TouchableOpacity,
    InteractionManager,
    Alert,
} from 'react-native';

import {
    UIConstants,
    Colors,
    FontSizes,
    PubSubTopics,
    CommonData,
    Routes,
} from '../../common';

import ConfirmDialog from '../../components/dialog';
import Images from '../../images';

import LoginContainer from '../../login/containers/loginContainer';

import Icon from 'react-native-vector-icons/Ionicons';
import PubSub from 'pubsub-js';

import * as ActionTypes from '../../actions/types';
import {resetPassword, logout, clearActionType} from '../../actions';

const WINDOW_HEIGHT = Dimensions.get('window').height;

class MyResetPwd extends Component {
    constructor(props) {
        super(props);

        this.onBackPress = this.onBackPressFunc.bind(this);
        this.onSavePress = this.onSavePressFunc.bind(this);
        this.onOriginPwdInputFocus = this.onOriginPwdInputFocusFunc.bind(this);
        this.onOriginPwdInputBlur = this.onOriginPwdInputBlurFunc.bind(this);
        this.clearOriginPwdInput = this.clearOriginPwdInputFunc.bind(this);
        this.onNewPwdInputFocus = this.onNewPwdInputFocusFunc.bind(this);
        this.onNewPwdInputBlur = this.onNewPwdInputBlurFunc.bind(this);
        this.clearNewPwdInput = this.clearNewPwdInputFunc.bind(this);
        this.onDcheckPwdInputFocus = this.onDcheckPwdInputFocusFunc.bind(this);
        this.onDcheckPwdInputBlur = this.onDcheckPwdInputBlurFunc.bind(this);
        this.clearDcheckPwdInput = this.clearDcheckPwdInputFunc.bind(this);
        // this.showInfoModal = this.showInfoModalFunc.bind(this);

        this.isOriginPwdInputFocused = false;
        this.isNewPwdInputFocused = false;
        this.isDcheckPwdInputFocused = false;

        this.state = {
            originpwd: '',
            newpwd: '',
            dcheckpwd: '',
            title: '',
            content: '',
            confirmLabel: '',
            cancelLabel: '',
            confirmFunc: () => null,
            cancelFunc: () => null,
            dialogType: '',
            iconType: '',
        };
    }

    componentDidMount() {
    }

    componentWillReceiveProps(nextProps) {
        PubSub.publish(PubSubTopics.SPINKIT_MODAL_CLOSE);
        switch (nextProps.actionType) {
            case ActionTypes.MY_RESETPWD_RESET_SUCCESS:
                this.setState({
                    originpwd: '',
                    newpwd: '',
                    dcheckpwd: ''
                });

                // const {navigatorRoot} = this.props;
                // navigatorRoot.pop();

                // PubSub.publish(PubSubTopics.TOAST_MODAL_OPEN, '密码修改成功，建议重新登录验证新密码');
                if (this.props.route.from && this.props.route.from === Routes.LOGIN) {
                    this.setState({
                        title: UIConstants.my.kindlyPrompt,
                        content: '密码修改成功，请重新登陆！',
                        confirmLabel: '确定',
                        cancelLabel: '',
                        confirmFunc: () => {this.logout()},
                        cancelFunc: () => null,
                        dialogType: 'confirmOnly',
                        iconType: 'none',
                    });

                    this.confirmDialogPanda && this.confirmDialogPanda.open();
                }
                else {
                    // 在ConfirmDialog中告知用户进行重新登陆
                    let params = {
                        title: UIConstants.my.kindlyPrompt,
                        content: '密码修改成功，请重新登陆！',
                        confirmLabel: '确定',
                        cancelLabel: '',
                        confirmCallback: () => {this.logout()},
                        cancelCallback: () => null,
                        dialogType: 'confirmOnly',
                        iconType: 'none',
                    };
                    PubSub.publish(PubSubTopics.CONFIRM_DIALOG_OPEN, params);
                }
                break;
            case ActionTypes.MY_RESETPWD_RESET_FAILED:
                console.log(ActionTypes.MY_RESETPWD_RESET_FAILED+': '+nextProps.msg);
                PubSub.publish(PubSubTopics.TOAST_MODAL_OPEN, '失败: '+nextProps.msg);
                break;
            default:
                PubSub.publish(PubSubTopics.TOAST_MODAL_OPEN, nextProps.msg);
                break;
        }
    }

    logout() {
        CommonData.isAppInitAfterLogin=true;

        if (this.props.route && this.props.route.from && this.props.route.from === Routes.LOGIN) {
            const { dispatch, navigatorRoot } = this.props;
        
            // 清理login state树
            // dispatch(clearLogin());
            dispatch(clearActionType());
            navigatorRoot.resetTo({
                name: Routes.LOGIN,
                component: LoginContainer,
                isLogout: true,
            });
        }
        else {
            PubSub.publish(PubSubTopics.SPINKIT_MODAL_OPEN, UIConstants.logout.logoutTips);
            
            setTimeout(() => {
                const { dispatch } = this.props;
                dispatch(logout());
            }, 1000);
        }
    }

    onChangeOriginPassword(pwd) {
        if (this.originPwdInput.isFocused() && pwd !== '') {
            this.isOriginPwdInputFocused = true;
        }
        else {
            this.isOriginPwdInputFocused = false;
        }

        this.setState({
            originpwd: pwd,
        });
    }

    onChangeNewPassword(pwd) {
        if (this.newPwdInput.isFocused() && pwd !== '') {
            this.isNewPwdInputFocused = true;
        }
        else {
            this.isNewPwdInputFocused = false;
        }

        this.setState({
            newpwd: pwd,
        });
    }

    onChangeDcheckPassword(pwd) {
        if (this.dcheckPwdInput.isFocused() && pwd !== '') {
            this.isDcheckPwdInputFocused = true;
        }
        else {
            this.isDcheckPwdInputFocused = false;
        }

        this.setState({
            dcheckpwd: pwd,
        });
    }

    onBackPressFunc() {
        if (this.props.route && this.props.route.from && this.props.route.from === Routes.LOGIN) {
            const { dispatch, navigatorRoot } = this.props;
        
            // 清理login state树
            // dispatch(clearLogin());
            dispatch(clearActionType());
            navigatorRoot.resetTo({
                name: Routes.LOGIN,
                component: LoginContainer,
                isLogout: true,
            });
        }
        else {
            const {navigatorRoot} = this.props;
            InteractionManager.runAfterInteractions(() => {
                navigatorRoot.pop();
            });
        }
    }

    onSavePressFunc() {
        let errorMsg = '';
        if (this.state.originpwd === '') {
            errorMsg = '原密码不能为空！';
            PubSub.publish(PubSubTopics.TOAST_MODAL_OPEN, errorMsg);
            this.originPwdInput.focus();
            return;
        }
        if (this.state.newpwd === '') {
            errorMsg = '新密码不能为空！';
            PubSub.publish(PubSubTopics.TOAST_MODAL_OPEN, errorMsg);
            this.newPwdInput.focus();
            return;
        }
        if (this.state.dcheckpwd === '') {
            errorMsg = '确认密码不能为空！';
            PubSub.publish(PubSubTopics.TOAST_MODAL_OPEN, errorMsg);
            this.dcheckPwdInput.focus();
            return;
        }
        if (this.state.newpwd && this.state.dcheckpwd && this.state.newpwd !== this.state.dcheckpwd) {
            errorMsg = '新密码和确认密码不相同，请确认后再提交！';
            PubSub.publish(PubSubTopics.TOAST_MODAL_OPEN, errorMsg);
            this.dcheckPwdInput.focus();
            return;
        }
        
        this.originPwdInput.blur();
        this.newPwdInput.blur();
        this.dcheckPwdInput.blur();

        PubSub.publish(PubSubTopics.SPINKIT_MODAL_OPEN, UIConstants.my.resetingPwd);

        setTimeout(() => {
            const {dispatch} = this.props;
            dispatch(resetPassword(this.state.originpwd, this.state.newpwd, this.state.dcheckpwd));
        }, 500);
    }

    // “旧密码”输入框的三个方法
    onOriginPwdInputFocusFunc() {
        if (this.state.originpwd !== '') {
            this.isOriginPwdInputFocused = true;
        }
        this.setState({});
    }

    onOriginPwdInputBlurFunc() {
        this.isOriginPwdInputFocused = false;
        this.setState({});
    }

    clearOriginPwdInputFunc() {
        this.isOriginPwdInputFocused = false;
        this.setState({
            originpwd: '',
        });
    }

    // “新密码”输入框的三个方法
    onNewPwdInputFocusFunc() {
        if (this.state.newpwd !== '') {
            this.isNewPwdInputFocused = true;
        }
        this.setState({});
    }

    onNewPwdInputBlurFunc() {
        this.isNewPwdInputFocused = false;
        this.setState({});
    }

    clearNewPwdInputFunc() {
        this.isNewPwdInputFocused = false;
        this.setState({
            newpwd: '',
        });
    }

    // “确认密码”输入框的三个方法
    onDcheckPwdInputFocusFunc() {
        if (this.state.dcheckpwd !== '') {
            this.isDcheckPwdInputFocused = true;
        }
        this.setState({});
    }

    onDcheckPwdInputBlurFunc() {
        this.isDcheckPwdInputFocused = false;
        this.setState({});
    }

    clearDcheckPwdInputFunc() {
        this.isDcheckPwdInputFocused = false;
        this.setState({
            dcheckpwd: '',
        });
    }

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.headers}>
                    <TouchableOpacity style={styles.headerback} onPress={this.onBackPress}>
                        <Image source={Images.Back} style={styles.headerbackicon} resizeMode={Image.resizeMode.contain} />
                        <Text style={styles.headerbacktext}>{UIConstants.my.back}</Text>
                    </TouchableOpacity>
                    <Text style={styles.headertext} numberOfLines={1}>
                       {UIConstants.my.resetPwd}
                    </Text>
                    <TouchableOpacity style={styles.headerback} onPress={this.onSavePress}>
                        <Text style={styles.headerbacktext}>{UIConstants.my.savePwd}</Text>
                    </TouchableOpacity>
                </View>
                
                <View style={styles.emptyview} />
                <View style={styles.splitter} />
                <View style={styles.itemview}>
                    <Text style={styles.itemname} >{UIConstants.my.originPwd}</Text>
                    <TextInput  
                        ref={(ref) => {this.originPwdInput = ref}}
                        style={styles.inputBox}
                        placeholder={UIConstants.my.originPwd_placeholder}
                        value={this.state.originpwd}
                        underlineColorAndroid={'transparent'}
                        autoCapitalize={'none'}
                        autoCorrect={false}
                        secureTextEntry={true}
                        onChangeText={(password) => {this.onChangeOriginPassword(password)}}
                        onFocus={this.onOriginPwdInputFocus}
                        onBlur={this.onOriginPwdInputBlur}
                        maxLength={20}
                    />
                    {
                        this.isOriginPwdInputFocused ? 
                        <TouchableOpacity onPress={this.clearOriginPwdInput}>
                            <Icon style={styles.clearicon} name={'md-close'} size={WINDOW_HEIGHT / 12 / 2} color={Colors.gray} />
                        </TouchableOpacity>
                        : null
                    }
                </View>
                <View style={styles.indentsplitter} />
                <View style={styles.itemview}>
                    <Text style={styles.itemname} >{UIConstants.my.newPwd}</Text>
                    <TextInput  
                        ref={(ref) => {this.newPwdInput = ref}}
                        style={styles.inputBox}
                        placeholder={UIConstants.my.newPwd_placeholder}
                        value={this.state.newpwd}
                        underlineColorAndroid={'transparent'}
                        autoCapitalize={'none'}
                        autoCorrect={false}
                        secureTextEntry={true}
                        onChangeText={(password) => {this.onChangeNewPassword(password)}}
                        onFocus={this.onNewPwdInputFocus}
                        onBlur={this.onNewPwdInputBlur}
                        maxLength={20}
                    />
                    {
                        this.isNewPwdInputFocused ? 
                        <TouchableOpacity onPress={this.clearNewPwdInput}>
                            <Icon style={styles.clearicon} name={'md-close'} size={WINDOW_HEIGHT / 12 / 2} color={Colors.gray} />
                        </TouchableOpacity>
                        : null
                    }
                </View>
                <View style={styles.indentsplitter} />
                <View style={styles.itemview}>
                    <Text style={styles.itemname} >{UIConstants.my.dcheckPwd}</Text>
                    <TextInput  
                        ref={(ref) => {this.dcheckPwdInput = ref}}
                        style={styles.inputBox}
                        placeholder={UIConstants.my.dcheckPwd_placeholder}
                        value={this.state.dcheckpwd}
                        underlineColorAndroid={'transparent'}
                        autoCapitalize={'none'}
                        autoCorrect={false}
                        secureTextEntry={true}
                        onChangeText={(password) => {this.onChangeDcheckPassword(password)}}
                        onFocus={this.onDcheckPwdInputFocus}
                        onBlur={this.onDcheckPwdInputBlur}
                        maxLength={20}
                    />
                    {
                        this.isDcheckPwdInputFocused ? 
                        <TouchableOpacity onPress={this.clearDcheckPwdInput}>
                            <Icon style={styles.clearicon} name={'md-close'} size={WINDOW_HEIGHT / 12 / 2} color={Colors.gray} />
                        </TouchableOpacity>
                        : null
                    }
                </View>
                <View style={styles.splitter} />
                
                <ConfirmDialog
                    ref={(ref) => {this.confirmDialogPanda = ref}}
                    title={this.state.title}
                    content={this.state.content}
                    confirmLabel={this.state.confirmLabel}
                    cancelLabel={this.state.cancelLabel}
                    confirmCallback={this.state.confirmFunc}
                    cancelCallback={this.state.cancelFunc}
                    type={this.state.dialogType}
                    iconType={this.state.iconType}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'transparent',
    },
    headers: {
        height: 60,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        borderBottomWidth: 0.5,
        borderBottomColor: Colors.gray,
        backgroundColor: Colors.appHeaderBackground,
    },
    headertext: {
        flex: 1,
        fontSize: FontSizes.soiHeader,
        color: Colors.appHeaderText,
        textAlign: 'center',
        alignSelf: 'center',
        marginBottom: -12,
    },
    headerback: {
        flexDirection: 'row',
        marginBottom: -12,
        alignItems: 'center',
        padding: 8,
    },
    headerbackicon: {
        width: 20,
        height: 20,
    },
    headerbacktext: {
        fontSize: 17,
        color: Colors.appHeaderText,
    },
    itemviewtrans: {
        flexDirection: 'row',
        paddingTop: 14,
        paddingBottom: 14,
        paddingLeft: 20,
        paddingRight: 12,
        backgroundColor:Colors.appBackground
    },
    itemview: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#FFFFFF'
    },
    itemcontent: {
        fontSize: FontSizes.itemWord,
        color: Colors.myItem
    },
    itemcontentgray: {
        fontSize: FontSizes.itemWord,
        color: Colors.gray,
        textDecorationLine:'underline'
    },
    itemname: {
        fontSize: FontSizes.itemWord,
        color: Colors.myItem,
        marginLeft: 20,
    },
    itemtext: {
        flex: 1,
        fontSize: FontSizes.itemWord,
        color: Colors.myItem,
        // marginLeft: 20,
        marginTop: (WINDOW_HEIGHT / 12 - 8) / 3,
        marginBottom: (WINDOW_HEIGHT / 12 - 8) / 3
    },
    inputBox: {
        flex: 1,
        // marginLeft: 8,
        marginRight: 24,
        height: WINDOW_HEIGHT / 12 - 8,
        fontSize: FontSizes.itemWord,
        alignItems: 'center',
        alignSelf: 'center',
        justifyContent: 'center',
        // backgroundColor: 'red'
    },
    splitter: {
        borderColor: Colors.lightGray,
        borderWidth: 0.5
    },
    indentsplitter: {
        borderColor: Colors.lightGray,
        borderWidth: 0.5,
        marginLeft: 20
    },
    emptyview: {
        height: 20,
        backgroundColor: 'transparent',
    },
    clearicon: {
        // marginLeft: 24,
        marginRight: 20,
    },
});

export default MyResetPwd;